﻿#include "addfriendwidget.h"
#include "ui_addfriendwidget.h"

AddFriendWidget::AddFriendWidget(QString sender,std::unordered_map<std::string,Firend>* friends,QWidget *parent) :
    QWidget(parent),
    sender(sender),
    friends(friends),
    sockCli(sockCli),
    ui(new Ui::AddFriendWidget)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose, true);
    sockCli = SocktetUtil::openClientSocket("47.113.150.167", 6543);//192.168.147.128
}

AddFriendWidget::~AddFriendWidget()
{
    qDebug()<<u8"AddFriendWidget析构";
    m.messageType = 1;
    send(sockCli,(char*)&m,sizeof(m),0);
    closesocket(sockCli);
    delete ui;
}
void AddFriendWidget::closeEvent(QCloseEvent *event){
    this->close();
}
void AddFriendWidget::on_send_clicked()
{
    //1.获取接受者
    recever = ui->recever->text();
    if(recever.size() != 4){
        QMessageBox::information(this,u8"提示",u8"输入格式有误");
        return;
    }
    //判断接受者是不是已经是好友
    if(friends->find(recever.toStdString()) != friends->end()){
        QMessageBox::information(this,u8"提示",u8"该用户已经是您的好友！");
        return;
    }
    //2.获取备注
    otherMessage = ui->otherMessage->toPlainText();
    //3.发送
    m.messageType = 5;
    strcpy(m.sender,sender.toStdString().c_str());
    strcpy(m.recevicer,recever.toStdString().c_str());
    strcpy(m.messageContent,otherMessage.toStdString().c_str());
    qDebug()<<send(sockCli,(char*)&m,sizeof(m),0);
    //4.等待服务器反馈
    qDebug()<<recv(sockCli,(char*)&m,sizeof(m),0);
    //5.成功关闭，失败不关闭
    if(strncmp(m.messageContent,"S",1) == 0){//成功
        QMessageBox::information(this,u8"提示",u8"发送成功！");
        this->close();
    }else{
        QMessageBox::information(this,u8"提示",u8"该用户不存在！");
        ui->recever->setText("");
        ui->otherMessage->setText("");
    }
}
